package com.example.smartlearning.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.smartlearning.entity.ResultEntity;
import com.example.smartlearning.service.AIService;
import com.example.smartlearning.tool.BaiDU.FaceTool;
import com.example.smartlearning.tool.BaiDU.OCR;
import com.example.smartlearning.tool.BaiDU.Similar;
import com.example.smartlearning.tool.DownloadPicture;
import com.example.smartlearning.tool.KoDoTool;
import com.example.smartlearning.tool.Translators;
import com.example.smartlearning.tool.XingHuo.AIDialogue;
import com.example.smartlearning.tool.XingHuo.QucikMath.WebITR;
import com.google.gson.JsonObject;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.UUID;

@Service
public class AIServiceImpl implements AIService {
    private static final Logger logger = LoggerFactory.getLogger(AIServiceImpl.class);//日志。getLogger需要传入当前的类名

    @Resource
    AIDialogue aiDialogue;

    @Resource
    KoDoTool koDoTool;
    @Resource
    DownloadPicture downloadPicture;

    @Resource
    Translators translators;
    @Resource
    WebITR webITR;

    @Resource
    OCR ocr;

    @Resource
    FaceTool faceTool;

    @Resource
    Similar similar;


    @Value("/www/wwwroot/SmartLearning/pic/")
    private String localFilePath;//本地文件存储地址


    @Override
    public String AIDialog(String text) {
        try {
            aiDialogue.AIDialogues(text);
            Thread.currentThread().sleep(7000);//因为星火是异步调用的  所以需要线程休眠3秒
            Object test= AIDialogue.answer;
//            while (true) {
//                if (AIDialogue.flag) {
//                    test = AIDialogue.answer;
//                    break;
//                }
//            }
            System.out.println();
            return ResultEntity.success(test);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getLocalizedMessage());
            return ResultEntity.fail(-10004);
        }

    }

    @Override
    public String AiITR(MultipartFile file) {//图片速算识别功能  传入图片文件
        String picture = upFile(file);//返回七牛云的路径
        try {
            downloadPicture.downLoad(picture);//下载图片到本地
            String ITRResult = webITR.ITR();//返回处理结果
            System.out.println("图片下载完毕");
            return ResultEntity.success(ITRResult);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getLocalizedMessage());
            return ResultEntity.fail(-10004);
        }
    }

    @Override
    public String upFile(MultipartFile file) {
        //上传文件返回一个url
        String SuffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));//获取文件后缀名
        String FileNewName = UUID.randomUUID() + SuffixName;//新的文件名
        File dest = new File(localFilePath + FileNewName);//生成新的文件
        if (!dest.getParentFile().exists()) {//判定文件夹是否存在
            dest.getParentFile().mkdir();//生成文件夹
        }
        try {
            file.transferTo(dest);//将临时文件转为正式文件
            return koDoTool.UploadFile(localFilePath + FileNewName);//返回七牛云的文件路径字符串
        } catch (Exception e) {
            logger.error(e.getMessage());//输出日志
            return ResultEntity.fail(-10001);//返回错误代码
        }
    }

    /**
     * @param SourceLanguage 需要翻译的文本格式
     * @param TargetLanguage 目标文本格式
     * @param SourceText     需要翻译的字符
     * @return 返回翻译结果
     */
    @Override
    public String AITranslate(String SourceLanguage, String TargetLanguage, String SourceText) {
        try {
            String result = translators.translate(SourceLanguage, TargetLanguage, SourceText);
            return ResultEntity.success(result);
        } catch (Exception e) {
            logger.error(e.getMessage());//输出日志
            return ResultEntity.fail(-10001);//返回错误代码
        }
    }

    /**
     * 调用百度的ocr接口 传入一个url
     * @param url url
     * @return 返回
     */
    @Override
    public String Ocr(String url) {
        try {
            System.out.println(url+"获取到url");
            String result = ocr.getWord(url);
            //对result进行处理
            JSONObject jsonObject = JSON.parseObject(result);
            System.out.println(jsonObject.get("words_result_num"));//4
            ArrayList words_result = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("words_result")),ArrayList.class);
            System.out.println(words_result.get(1));
            String text = "";
            for (int i = 0;i<(Integer)jsonObject.get("words_result_num");i++){
                text+=words_result.get(i);
            }
            text = text.replace("words","");
            text = text.replace("{","");
            text = text.replace("}","");
            text = text.replace(":","");
            text = text.replace("\"","");
            text+="是出自哪本书的内容";
            System.out.println(text);
            aiDialogue.AIDialogues(text);
            Thread.sleep(7000);//因为星火是异步调用的  所以需要线程休眠3秒
            Object test= AIDialogue.answer;
            return ResultEntity.success(test);
        } catch (Exception e) {
            logger.error(e.getMessage());//输出日志
            return ResultEntity.fail(-10001);//返回错误代码
        }
    }

    @Override
    public String face(String url1, String url2) {
        try {
            String result = faceTool.face(url1,url2);
            JSON json = JSON.parseObject(result);
            System.out.println(result);
            return ResultEntity.success(json);
        } catch (Exception e) {
            logger.error(e.getMessage());//输出日志
            return ResultEntity.fail(-10001);//返回错误代码
        }
    }

    @Override
    public String similar(String text1, String text2) {
        try {
            String result = similar.similar(text1,text2);
            JSON json = JSON.parseObject(result);
            System.out.println(result);
            return ResultEntity.success(json);
        } catch (Exception e) {
            logger.error(e.getMessage());//输出日志
            return ResultEntity.fail(-10001);//返回错误代码
        }
    }
}
